package com.hexiang.rocketmq.mq.producer;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class AsyncProducer {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送异步消息 在SendCallback中可处理相关成功失败时的逻辑
     */
    public void sendAsyncMsg(String msgBody) {
        rocketMQTemplate.asyncSend("TopicTest", MessageBuilder.withPayload(msgBody).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                // 处理消息发送成功逻辑
                System.out.printf("%s%n", sendResult);
            }

            @Override
            public void onException(Throwable e) {
                // 处理消息发送异常逻辑
                System.out.printf("%s%n", e);

            }
        });
    }

}